package com.xc58.highreactor.server.core.scanner;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import com.google.common.base.Strings;
import com.xc58.highreactor.annotation.RPCMethod;
import com.xc58.highreactor.exception.NoImplClassFoundException;
import com.xc58.highreactor.exception.UnsupportMultiRPCImplException;


@SuppressWarnings({"rawtypes"})
public class ServiceMapping {

	/**
	 *   init var. 
	 */
	private String serviceName;
	
	private Map<String,Method> mapping = new HashMap<String,Method>();
	
	private boolean useFirst = true;
	
	private HashSet<String> allClass = new HashSet<String>();

	public ServiceMapping(String serviceName, Class interfaceClass, List<String> implClass){
		this.serviceName = serviceName;
		Method[] methods = interfaceClass.getMethods();
		
		for (Method cur : methods) {
			RPCMethod annotation = cur.getAnnotation(RPCMethod.class);
			if(annotation != null){
				String methodName = annotation.name().trim();
				if(Strings.isNullOrEmpty(methodName)){
					methodName = cur.getName();
				}
				mapping.put(methodName, cur);
			}
		}
		
		for (String impl : implClass) {
			if(!Strings.isNullOrEmpty(impl.trim())){
				allClass.add(impl);
			}
		}
		
		if(allClass.size() == 0){
			throw new NoImplClassFoundException("Service [%s] don't have impl Class");
		}
		
		if(allClass.size() > 1){
			if(mapping.get("rpcSelect") == null){
				throw new UnsupportMultiRPCImplException(String.format("Service [%s] is use multi implClass, but don't add rpcSelect method. will random use the impl class",serviceName));
			}else{
				useFirst = false;
			}
		}
	}
	
	public String getServiceName(){
		return serviceName;
	}
	
	
	

}
